#include "Acceptor.hpp"
#include <asm-generic/socket.h>
#include <sys/socket.h>

namespace wd
{
Acceptor::Acceptor(const string &ip,unsigned short port)
:_socket()
,_address(ip,port)
{}

void Acceptor::ready(){
   bind();
   listen();
   setAddrReuse();
   setPortReuse();
}

int Acceptor::accept(){
    int ret = ::accept(_socket.getFd(),nullptr,nullptr);
    if (ret <0){
        perror("accept");
    }
    return ret;
}

int Acceptor::getFd()const{
    return _socket.getFd();
}

void Acceptor::bind(){
    int ret =::bind(_socket.getFd(),(const struct sockaddr*)_address.getSockAddrPtr(),sizeof(_address));
    if(ret <0){
        perror("bind");
    }
}

void Acceptor::listen(){
    int ret = ::listen(_socket.getFd(),20000);
    if(ret <0){
        perror("listen");
    }
}

void Acceptor::setAddrReuse(){
    int one =1;
    int ret = setsockopt(_socket.getFd(),SOL_SOCKET,SO_REUSEADDR,&one,sizeof(one));
    if(ret <0){
        perror("setsockopt");
    }
}

void Acceptor::setPortReuse(){
    int one =1;
    int ret = setsockopt(_socket.getFd(),SOL_SOCKET,SO_REUSEPORT,&one,sizeof(one));
    if(ret <0){
        perror("setsockopt");
    }
}

}//end of namespace
